package com.zlt.appparking.listener;

import com.zlt.appparking.entity.UserVip;
import com.zlt.appparking.entity.UserVipExample;
import com.zlt.appparking.entity.VipType;
import com.zlt.appparking.entity.VipTypeExample;
import com.zlt.appparking.mapper.UserVipMapper;
import com.zlt.appparking.mapper.VipTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    UserVipMapper userVipMapper;

    @Autowired
    private VipTypeMapper vipTypeMapper;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 过期key
        String expiredKey = message.toString();
        System.out.println(expiredKey + "过期了");
        if(expiredKey.contains("_")){//说明是会员过期
            String[] data = expiredKey.split("_");
            String auId = data[0];//用户id
            int plId = 0;
            if (data.length >1){
                plId = Integer.parseInt(data[1]);//停车场id
            }
            VipTypeExample vipTypeExample = new VipTypeExample();
            vipTypeExample.createCriteria().andPlIdEqualTo(plId);
            //查询停车场对应的会员类型
            List<VipType> vipTypes = vipTypeMapper.selectByExample(vipTypeExample);
            int vtid = vipTypes.get(0).getVtId();//类型id
            UserVipExample userVipExample = new UserVipExample();
            userVipExample.createCriteria().andAuIdEqualTo(auId).andVtIdEqualTo(vtid).andUvStateEqualTo((byte)0);
            //查询满足 当前用户+停车场+有效期内 的用户vip数据
            UserVip userVip = userVipMapper.selectByExample(userVipExample).get(0);
            userVip.setUvState((byte) 1);//设置会员失效
            userVipMapper.updateByPrimaryKeySelective(userVip);
        }
        // 下面可以通过redis工具获取值或者执行业务逻辑
    }

    public RedisKeyExpirationListener(RedisMessageListenerContainer redisMessageListenerContainer ){
        super(redisMessageListenerContainer);
    }
}
